import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_clx_base/utils/log_utils.dart';
import 'package:flutter_clx_base/widget/normal_dialog.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import 'permission_helper.dart';

S? findOtherLogic<S>({String? tag}) {
  if (Get.isRegistered<S>(tag: tag)) {
    return Get.find<S>(tag: tag);
  }
  return null;
}

// 任意类型转String
String getTXTString(dynamic data) {
  if (data is String) {
    return data;
  } else if (data is int) {
    return data.toString();
  } else if (data is double) {
    return data.toString();
  } else if (data is bool) {
    return data.toString();
  } else {
    return "";
  }
}

// 格式化小数两位
String formatDouble(number, {nullTxt = "-"}) {
  if (number == null || number == "") {
    return nullTxt;
  }
  double num;
  try {
    num = double.parse(number.toString());
  } catch (e) {
    loggerNoStack.d("转换异常:$e");
    return nullTxt;
  }
  if ((num.toString().length - num.toString().lastIndexOf(".") - 1) < 2) {
    //小数点后有几位小数
    return num.toStringAsFixed(2)
        .substring(0, num.toString().lastIndexOf(".") + 2 + 1)
        .toString();
  } else {
    return num.toString()
        .substring(0, num.toString().lastIndexOf(".") + 2 + 1)
        .toString();
  }
}

// double格式化 默认 0.00
String formatDoubleZero(number) {
  return formatDouble(number, nullTxt: "0.00");
}

// int 转换 默认0
String formatInt(number, {nullTxt = "-"}) {
  if (number == null || number == "") {
    return nullTxt;
  }
  int num;
  try {
    num = int.parse(number.toString());
  } catch (e) {
    loggerNoStack.i("转换异常:$e");
    return nullTxt;
  }
  return num.toString();
}

// int格式化 默认 0
String formatIntZero(number) {
  return formatInt(number, nullTxt: "0");
}

/// 动态申请权限
/// onGranted 获取权限
/// onRefuse 拒绝权限
/// onSettings 手动设置权限
/// onCancelSettings 不手动设置权限
requestPermission({
  VoidCallback? onGranted,
  VoidCallback? onRefuse,
  VoidCallback? onSettings,
  VoidCallback? onCancelSettings,
  required String? toSettingTip,
  required List<Permission> permissionList,
}) {
  PermissionHelper.request(
    permissionList,
    onSuccess: onGranted, // 授权权限回调,
    onFailed: onRefuse, // 权限拒绝回调
    onOpenSetting: () {
      Get.dialog(
          PopScope(
            canPop: false,
            child: NormalDialog(
              title: "温馨提示",
              content: toSettingTip,
              cancelBtnText: "稍后提醒",
              confirmBtnText: "去授权",
              onConfirm: () {
                openAppSettings();
                onSettings?.call(); // 跳转设置页面回调
              },
              onCancel: onCancelSettings, // 不跳转设置页面回调
            ),
          ),
          barrierDismissible: false);
    },
  );
}
